package com.qf.exception;

import com.qf.util.ResultCode;
import com.qf.util.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * #TODO 自定义统一异常处理类
 */
@RestControllerAdvice //@ResponseBody
@Slf4j
public class ControllerExceptionHandler {

    /*
    * @RestControllerAdvice都是对Controller进行增强的，可以全局捕获spring mvc抛的异常。
    * @ExceptionHandler(value = Exception.class)的作用是用来捕获指定的异常。
    * */

    /**
     * @TODO id大于100
     * @param e
     * @return
     */
    @ExceptionHandler
    public Object runTimeExceptionHandler(RuntimeException e){

        return new ResultJson<>(null,"5000",e.getMessage());

    }

    /**
     * #TODO 参数类型错误
     * @param e
     * @return
     */
    @ExceptionHandler
    public Object methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException e){

        return new ResultJson<>(null,ResultCode.PARAMS_ERROR);

    }

    /**
     * @TODO 没加参数
     * @param e
     * @return
     */
    @ExceptionHandler
    public Object exceptionHandler(Exception e){

        return new ResultJson<>(null, ResultCode.EXCEPTION_SERVER);

    }


    /**
     * 参数校验异常类BindException
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Object handleBindException(BindException ex){
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
        return  new ResultJson(fieldError.getDefaultMessage(),ResultCode.FAIL);
    }
    /**
     * 参数校验异常类MethodArgumentNotValidException
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Object handleBindException(MethodArgumentNotValidException ex){
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());

        return  new ResultJson(fieldError.getDefaultMessage(),ResultCode.FAIL);
    }

}
